<?php
session_start();
$lib_dir = str_ireplace("ajax", "lib", dirname(__FILE__));
require_once $lib_dir.'/config.php';
require_once $lib_dir.'/facebook.php';
require_once $lib_dir.'/util.php';
require_once $lib_dir.'/friend.php';
require_once $lib_dir.'/friends.php';

//if graph data is already loaded
//if(isset($_SESSION['friends'])){
//    
//    print($_SESSION['friends']);
//    
//} else {

    if(!isset($_SESSION['fb_session']) && !isset($_REQUEST['signed_request']) ){
        print('{ "error": "Invalid request is detected. Program abort." }');
        exit();
    }
    
    $facebook = new Facebook(array(
        'appId' => FB_APP_ID,
        'secret' => FB_APP_SECRET
    ));
    
    if(isset($_SESSION['fb_session'])){
        $facebook->setSession($_SESSION['fb_session']);        
    }
    
    $session = $facebook->getSession();
    
    $friends = null;
    if($session){
        try{
            $now = time();	
        	
            $friends = getFriends();
            
            error_log("Elapsed time for getFriends() with ".count($friends)." of friends : ".(time() - $now));
            $now = time();    
    		
            //JSON encoding
            $json = "[";
        
            $isFirst = true;
            foreach($friends as $f){
                if($mode == 0 || $f->getScore() != 0){
                    if(!$isFirst){
                        $json .= ',';
                    }
                    $json .= '{';
                    $json .= '"fId" : "'.$f->getfId().'",';
                    $json .= '"name" : "'.$f->getName().'",';
                    $json .= '"score" : "'.$f->getScore().'"';
                    $json .= '}';
                    $isFirst = false;
                }
            }
        
            $json .= "]";
    
            $_SESSION['friends'] = $json;
            
            //return output
            print $json;
                
        } catch (FacebookApiException $e){

            print('{"error":"'."Facebook error:".$e->getMessage().'"}');
        }
    }
//}